<?php
/**

*/
class Model_User
{
	protected  $db;

	public function __construct()
	{
		$this->db = Zend_Registry::get("db");
	}

	public function getUserByEmail($email)
	{
		$select  = $this->db->select()->from('user')->where('email = ?', $email);
		$user = $this->db->fetchRow($select);
		//App_Log::query($this->db);
		if (!$user) {
			throw new Exception("user with email [$email] does not exist!");
		}
		return $user;
	}

	public function getUserByApiKey($key)
	{
		$select = $this->db->select()->from('user')->where('api_key = ?', $key);
		$user = $this->db->fetchRow($select);
		//App_Log::query($this->db);
		if (!$user) {
			throw new Exception("user with api_key [$key] does not exist!");
		}
		return $user;
	}

	public function addUser($email, $timezone, $role, $password)
	{
		// generate unique id for the password salt
		$salt = strtolower(uniqid(rand(), true));

		// generate unique id for the user's api identifier
		$api_key = $this->generateApiKey();

		// and finally...one more for their initial api 'secret' key
		$api_secret_key = strtolower(uniqid(rand(), true));

		// create a password hash to save in the database
		$hashed_pwd = strtolower(md5($password . $salt));

		$data = array(
            'email' => $email,
            'timezone' => $timezone,
            'role' => $role,
			'password' => $hashed_pwd,
            'salt' => $salt,
            'api_key' => $api_key,
            'api_secret_key' => $api_secret_key,
            'created_at' => null // force the created_at to get current timestamp
		);
		
		$this->db->insert('user',$data);

		$user_id = $this->db->lastInsertId();

		//App_Log::query($this->db);

		return $user_id;
	}

	function updateUser($id, $email, $timezone, $role, $password=null)
	{
		$where = array('id = ?' => (int)$id);

		$data['email']=$email;
		$data['role']=$role;
		$data['timezone']=$timezone;

		if ($password !== null){
			// generate unique id (again) for the password salt
			$salt = strtolower(uniqid(rand(), true));
			$hashed_pwd = strtolower(md5($password . $salt));
			$data['salt']=$salt;
			$data['password']=$hashed_pwd;
		}

		$updated = $this->db->update('user', $data, $where);
		//App_Log::query($this->db);

		if ($updated) return true;
		else return false;
	}

	/**
	 *
	 * @return string; a unique API KEY for a new user
	 */
	private function generateApiKey()
	{
		// generate unique id for the user's key identifier
		$key = strtolower(uniqid(rand(), true));

		// the above code 'should' always create a unique id for the user
		// but...just in case of a collision, we keep trying until there is not one
		// in our database
		$select  = $this->db->select()->from('user')->where('api_key = ?', $key);
		while (($user = $this->db->fetchRow($select)) != null){
			$key = strtolower(uniqid(rand(), true));
		}
		//App_Log::query($this->db);
		return $key;

	}

	public static function str_makerand ($minlength, $maxlength) {
	    $charset = "abcdefghijklmnopqrstuvwxyz"; 
	    if ($minlength > $maxlength) 
	        $length = mt_rand ($maxlength, $minlength); 
	    else
	        $length = mt_rand ($minlength, $maxlength); 
	        
	      $key='';
	    for ($i=0; $i<$length; $i++) $key .= $charset[(mt_rand(0,(strlen($charset)-1)))]; 
	    return $key; 
	}

}